<template>
  <view class="goods-item" @click="clickFn">
    <view class="goods-item-left">
      <!-- 购物车组件，商品勾选与取消勾选 -->      
      <radio v-if="showRadio" color="#c00000" :checked="goods.state" @click="radioClick" />
      <image :src="goods.pic || defaultPic" class="goods-pic"></image>
    </view>
    <view class="goods-item-right">
      <view class="goods-name">{{ goods.goodsname }}</view>
      <view class="goods-info">
        <view class="goods-price">￥{{ Number(goods.price).toFixed(2) }}</view>
        <!-- 数字输入框 -->
        <uni-number-box v-if="showGoodsCount" v-model="goods.count" :min="1" @change="countChange"></uni-number-box>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref } from 'vue';
  const emits = defineEmits(["click", "radioChange", "countUpdate"]);
  const props = defineProps({
    // 背景颜色
    goods: {
      type: Object,
      default: () => {}
    },
    showRadio: {
      type: Boolean,
      default: false
    },
    showGoodsCount: {
      type: Boolean,
      default: false
    }
  });
  const defaultPic = ref('https://mmbiz.qpic.cn/sz_mmbiz_jpg/RibebLgyCicsxQrhkY9cWfKl4aonjpWMwuVsT6KYpjTUEJ2EE9nob3vakhQakMKJ2LxIdHGbDAEf4oia7aPcj6xRQ/640?wx_fmt=jpeg&from=appmsg&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1')
  
  function clickFn() {
    emits('click', props.goods)
  }
  
  // 购物车中的商品需要在cart.vue组件中进行结算,而不是在当前组件,所以将数据传到父组件比较合适
  // 如果购物车中只有一个商品（不存在点击的商品发生变化），多次点击change事件不会执行，需要使用click触发事件
  function radioClick(e) {
    emits('radioChange', {
      id: props.goods.id,
      state: !props.goods.state,
    })
  }
  function countChange(e) {
    emits('countUpdate', {
      id: props.goods.id,
      count: +e,
    })
  }
</script>

<style lang="scss" scoped>
  .goods-item {
    width: 750rpx;
    box-sizing: border-box;
    display: flex;
    padding: 10px 5px;
    border-bottom: 1px solid #f0f0f0;
    .goods-item-left {
      margin-right: 5px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .goods-pic {
        width: 100px;
        height: 100px;
        display: block;
      }
    }
    .goods-item-right {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .goods-name {
        font-size: 13px;
      }
      .goods-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .goods-price {
          color: #c00000;
          font-size: 16px;
        }
      }
    }
  }
</style>